# -*- coding: utf-8 -*-
"""
    Author:
    Date: 2018-10-25

    支付宝支付辅助类.
    参考地址: https://pypi.org/project/alipay-sdk-python/
"""
import logging
import traceback

from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayFundTransToaccountTransferModel import AlipayFundTransToaccountTransferModel
from alipay.aop.api.request.AlipayFundTransToaccountTransferRequest import AlipayFundTransToaccountTransferRequest
from alipay.aop.api.response.AlipayFundTransToaccountTransferResponse import AlipayFundTransToaccountTransferResponse

#  网站支付
# from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
# from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from alipay.aop.api.domain.AlipayTradeWapPayModel import AlipayTradeWapPayModel
from alipay.aop.api.request.AlipayTradeWapPayRequest import AlipayTradeWapPayRequest

from django.conf import settings
from utils.log import Log

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a',)
logger = logging.getLogger('')


def get_alipay_client():
    """ 得到客户端对象 """
    # 设置配置，包括支付宝网关地址、app_id、应用私钥、支付宝公钥等，其他配置值可以查看AlipayClientConfig的定义。
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = settings.ALIPAY_APP_ID
    alipay_client_config.app_private_key = settings.ALIPAY_APP_PRIVATE_KEY
    alipay_client_config.alipay_public_key = settings.ALIPAY_PUBLIC_KEY
    # alipay_client_config.sign_type = 'RSA'

    # 注意，一个alipay_client_config对象对应一个DefaultAlipayClient，定义DefaultAlipayClient对象后，
    # alipay_client_config不得修改，如果想使用不同的配置，请定义不同的DefaultAlipayClient。
    # logger参数用于打印日志，不传则不打印，建议传递。
    client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)
    return client


def trans_to_account(payer_show_name, out_biz_no, payee_account, cent, payee_real_name, remark):
    """ 单笔转账到支付宝账户

        参考地址：https://docs.open.alipay.com/309/106236/
    """
    if settings.DEBUG:
        return True, ''

    Log.info(f'Alipay trans to account ......: payee={payee_account}, amount={cent}')
    client = get_alipay_client()

    # 构造请求对象
    model = AlipayFundTransToaccountTransferModel()
    model.out_biz_no = out_biz_no
    model.payee_type = 'ALIPAY_LOGONID'
    model.payee_account = payee_account
    model.amount = cent/100.0
    model.payer_show_name = payer_show_name
    model.payee_real_name = payee_real_name
    model.remark = remark
    request = AlipayFundTransToaccountTransferRequest(biz_model=model)

    # 执行请求，执行过程中如果发生异常，会抛出，请打印异常栈
    response_content = None
    try:
        response_content = client.execute(request)
    except Exception as e:
        Log.error(traceback.format_exc())
        return False, 'exception.'

    if not response_content:
        Log.error("Alipay failed execute!")
        return False, 'lack content.'

    # 解析响应结果
    response = AlipayFundTransToaccountTransferResponse()
    response.parse_response_content(response_content)
    Log.info(response.body)
    if not response.is_success():
        # 如果业务失败，则从错误码中可以得知错误情况，具体错误码信息可以查看接口文档
        Log.error(f'Alipay trans to account failed: payee={payee_account}, amount={cent}, '
                  f'code={response.code}, msg={response.msg}, sub_code={response.sub_code}, sub_msg={response.sub_msg}')
        return False, f'code={response.code}, msg={response.msg}, sub_code={response.sub_code}, sub_msg={response.sub_msg}'

    # 如果业务成功，则通过response属性获取需要的值
    order_id = response.order_id
    out_biz_no = response.out_biz_no
    Log.info(f'Alipay response: order_id={order_id}, out_biz_no={out_biz_no}')
    return True, ''


def pay_on_web_page(uid, rmb, out_trade_no, total_amount):
    """ 手机网站支付
        参考地址: https://docs.open.alipay.com/203/105285/
    """
    if settings.DEBUG:
        return None

    Log.info(f'Alipay pay on page ......: out_trade_no={out_trade_no}, amount={total_amount}')
    client = get_alipay_client()

    # 构造请求对象
    model = AlipayTradeWapPayModel()  # 创建网站支付模型
    model.out_trade_no = out_trade_no  # 商户订单号，需要保证不重复
    model.total_amount = total_amount  # 订单金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
    model.subject = f'ID:{uid}, 注意防范扫码刷单骗局'  # 订单标题
    model.body = '购买钻石'  # 订单描述
    model.product_code = 'QUICK_WAP_WAY'  # 销售产品码，商家和支付宝签约的产品码。该产品请填写固定值：QUICK_WAP_WAY
    model.timeout_express = '30m'  # 订单过期关闭时长（分钟）

    pay_request = AlipayTradeWapPayRequest(biz_model=model)  # 通过模型创建请求对象
    pay_request.return_url = settings.ALIPAY_RETURN_URL % (uid, rmb)  # 设置返回地址
    pay_request.notify_url = settings.ALIPAY_NOTIFY_URL  # 设置回调通知地址
    response = client.page_execute(pay_request, http_method='GET')  # 获取支付链接
    return response


if __name__ == '__main__':
    print('ok')
